package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 1536. 排布二进制网格的最少交换次数
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/30 14:50
 */
public class MinSwaps {

    public static void main(String[] args) {
        MinSwaps test = new MinSwaps();

        // 3
        int[][] arr = {{0, 0, 1}, {1, 1, 0}, {1, 0, 0}};

        // -1
//        int[][] arr = {{0,1,1,0},{0,1,1,0},{0,1,1,0},{0,1,1,0}};

        // 0
//        int[][] arr = {{1,0,0},{1,1,0},{1,1,1}};

        int i = test.minSwaps(arr);
        System.out.println(i);
    }

    public int minSwaps(int[][] grid) {
        int length = grid.length;
        int[] arr = new int[length];
        for (int i = 0; i < length; i++) {
            int[] ints = grid[i];
            int count = 0;
            for (int j = length - 1; j >= 0; j--) {
                if (ints[j] == 1) {
                    break;
                } else {
                    count++;
                }
            }
            arr[i] = count;
        }
        int sum = 0;
        for (int i = length - 1; i >= 0; i--) {
            int count = 0;
            int j = 0;
            for (; j < length; j++) {
                int v = arr[j];
                if (v >= i) {
                    arr[j] = -1;
                    sum += count;
                    break;
                } else {
                    if (v != -1) {
                        count++;
                    }
                }
            }
            if (j == length) {
                return -1;
            }
        }
        return sum;
    }

}
